import requests
import simplejson
from zhipuai import ZhipuAI

from .model import Model


class GLMModel(Model):
    def __init__(self, api_key: str, model_name: int):
        self.model_name = model_name
        self.client = ZhipuAI(api_key=api_key)

    def make_request(self, content):
        try:
            response = self.client.chat.completions.create(
                model=self.model_name,  # 填写需要调用的模型名称
                messages=[
                    {"role": "user", "content": content},
                ],
                stream=True,
            )
            translation = ""
            for chunk in response:
                translation += chunk.choices[0].delta.content

            return translation, True
        except requests.exceptions.Timeout as e:
            raise Exception(f"请求超时：{e}")
        except requests.exceptions.RequestException as e:
            raise Exception(f"请求异常：{e}")
        except simplejson.errors.JSONDecodeError as e:
            raise Exception("Error: response is not valid JSON format.")
        except Exception as e:
            raise Exception(f"发生了未知错误：{e}")
